from agno.agent import Agent  # noqa
from agno.models.ollama import Ollama

from agno.os import AgentOS

from typing import Optional, Dict, Any
import requests

# agent = Agent(model=Ollama(id="qwen3:8b"), markdown=True)
# agent.print_response("Share a 2 sentence horror story")
# http://localhost:7777/docs
# https://qixinbo.info/2025/05/07/agno/

GEOCODING_URL = 'https://geocoding-api.open-meteo.com/v1/search'

def geocode_city_http(name: str) -> Optional[Dict[str, Any]]:
    try:
        resp = requests.get(GEOCODING_URL, params={
            'name': name, 'count': 1, 'language': 'zh', 'format': 'json'
        }, timeout=10)
        resp.raise_for_status()
        data = resp.json() or {}
        results = data.get('results') or []
        if not results:
            return None
        r0 = results[0]
        return {
            'name': r0.get('name'),
            'latitude': r0.get('latitude'),
            'longitude': r0.get('longitude'),
            'country': r0.get('country'),
            'timezone': r0.get('timezone')
        }
    except Exception as e:
        print('[Geocode] error:', e)
        return None
    


# 使用 agno 定义工具与 Agent
try:
    from agno.tools import tool
    HAVE_AGNO = True
except Exception as e:
    HAVE_AGNO = False
    print('Agno 未安装或导入失败：', e)

if HAVE_AGNO:
    @tool
    def geocode_city(name: str) -> dict:
        """将城市名称解析为经纬度与时区信息。
        返回: {name, latitude, longitude, country, timezone}
        """
        r = geocode_city_http(name)
        if not r:
            return {'error': f'未找到城市: {name}'}
        return r
    
analyst_agent = Agent(name="数据分析师", model=Ollama(id="qwen3:8b"),tools=[geocode_city], add_history_to_context=True,markdown=True,instructions=["我可以帮你查询天气信息"])

# 创建AgentOS实例
agent_os = AgentOS(agents=[analyst_agent])
# 获取FastAPI应用
app = agent_os.get_app()


# 启动服务
if __name__ =="__main__":     
    agent_os.serve(app="ollama_agno:app", reload=True)
